package com.wss.lsl.test.driven;

import java.util.ArrayList;
import java.util.List;

public class BackReadPrimes {

	private static boolean isPrimes(long num) {
		if (num == 2 || num == 3) {
			return true;
		}

		long mod6 = num % 6;
		if (mod6 != 1 && mod6 != 5) {
			return false;
		}

		int sqrt = (int) Math.sqrt(num);
		for (int i = 5; i <= sqrt; i += 6) {
			if (num % i == 0 || num % (i + 2) == 0) {
				return false;
			}
		}

		return true;
	}

	public static String backwardsPrime(long start, long end) {
		long count = end - start;

		List<String> nums = new ArrayList<>();
		int i = 0;
		StringBuilder sb = new StringBuilder();
		while (i <= count) {
			long num = start + i;
			i++;
			sb.setLength(0);
			sb.append(num);
			sb.reverse();

			int revNum = Integer.valueOf(sb.toString());
			if (revNum == num) {
				continue;
			}

			if (isPrimes(num) && isPrimes(revNum)) {
				nums.add(num + "");
			}
		}

		return String.join(" ", nums.toArray(new String[0]));
	}

	public static void main(String[] args) {
		long start = Long.valueOf(args[0]);
		long end = Long.valueOf(args[1]);
		System.out.println(backwardsPrime(start, end));
	}

}
